<template>
  <div class="tag-list-root">
    <el-tag
        :key="index"
        v-for="(tag,index) in dynamicTags"
        :closable="removeTag"
        :disable-transitions="false"
        @close="handleClose(tag)">
      {{ tag }}
    </el-tag>
    <el-input
        class="input-new-tag"
        v-if="inputVisible && addTag"
        v-model="inputValue"
        ref="saveTagInput"
        size="small"
        @keyup.enter.native="handleInputConfirm"
        @blur="handleInputConfirm"
    >
    </el-input>
    <el-button v-if="!inputVisible && addTag" class="button-new-tag" size="small" @click="showInput">+ 添加
    </el-button>
  </div>
</template>

<script>
import {isArr} from "@/utils/arrayUtil";
import {add} from "lodash";

export default {
  props: {
    value: {
      type: [Array]
    },
    addTag: {
      type: Boolean,
      default: false
    },
    removeTag: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val != null && JSON.stringify(val) != JSON.stringify(this.dynamicTags)) {
          this.dynamicTags = _.cloneDeep(val);
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    add,
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.submitData()
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
        this.submitData()
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    submitData() {
      this.$emit('change', this.dynamicTags)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
